package cn.haoma.base.common;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;

import cn.haoma.base.R;


/**
 * Created by ilioili on 2015/5/11.
 */
public abstract class BaseLocationActivity extends BaseActivity implements LocationSource, GeocodeSearch.OnGeocodeSearchListener {
    /**
     * 定位成功后回调函数
     */
    //    @Override
    //    public void onLocationChanged(AMapLocation aLocation) {
    //        if (mListener != null && aLocation != null) {
    //            mListener.onLocationChanged(aLocation);// 显示系统小蓝点
    //            LatLng latLng = new LatLng(aLocation.getLatitude(), aLocation.getLongitude());
    //            aMap.animateCamera( CameraUpdateFactory.changeLatLng(latLng));
    //        }
    //    }
    protected AMap aMap;
    protected LocationManagerProxy mAMapLocationManager;
    protected LocationSource.OnLocationChangedListener mListener;
    protected MapView mapView;
    private GeocodeSearch geocoderSearch;

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mAMapLocationManager != null) {
            mAMapLocationManager.destroy();
        }
        mAMapLocationManager = null;
    }

    /**
     * 根据经纬度获取地址
     *
     * @param lat
     * @param lng
     */
    protected void geocodeSearch(double lat, double lng) {
        RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat, lng), 200, GeocodeSearch.AMAP);
        if (null == geocoderSearch) {
            geocoderSearch = new GeocodeSearch(this);
            geocoderSearch.setOnGeocodeSearchListener(this);
        }
        geocoderSearch.getFromLocationAsyn(query);
    }

    /**
     * 把位置坐标（lat,lng)移动到地图中间
     *
     * @param lat
     * @param lng
     */
    protected void moveMapCenterTo(final double lat, final double lng) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                LatLng latLng = new LatLng(lat, lng);
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        });
    }

    /**
     * 移动并缩放地图视图，是两个点在视图内包含一个经纬度限制的区域，并且是最大可能的缩放级别。
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     */
    protected void moveMapToBound(final double lat1, final double lng1, final double lat2, final double lng2) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                LatLng latLngStart = new LatLng(lat1, lng1);
                LatLng latLngEnd = new LatLng(lat2, lng2);
                LatLngBounds latLngBounds = latLngStart.latitude < latLngEnd.latitude ? new LatLngBounds(latLngStart, latLngEnd) : new LatLngBounds(latLngEnd, latLngStart);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(latLngBounds, 20);
                aMap.moveCamera(cameraUpdate);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMapView(savedInstanceState);
    }

    /**
     * 初始化AMap对象
     */
    private void initMapView(Bundle savedInstanceState) {
        mapView = f(R.id.map);
        if (mapView == null) {
            throw new RuntimeException(getClass() + "的Layout文件中没有找到id为R.id.map的MapView");
        } else {
            mapView.onCreate(savedInstanceState);// 此方法必须重写
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.getUiSettings().setScaleControlsEnabled(false);
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        //        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        //        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
    }

    protected void startLocating(AMapLocationListener locationListener) {
        if (mAMapLocationManager == null) {
            mAMapLocationManager = LocationManagerProxy.getInstance(this);
            mAMapLocationManager.setGpsEnable(true);
            /*
             * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * 第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 */

            //            mAMapLocationManager.requestLocationUpdates(
            //                    LocationProviderProxy.AMapNetwork, 2000, 10, this);
        }
        //        mAMapLocationManager.requestLocationData(LocationManagerProxy.GPS_PROVIDER, 3000, 10, locationListener);
        mAMapLocationManager.requestLocationData(LocationProviderProxy.AMapNetwork, 3000, 10, locationListener);
    }

    protected void stopLocating() {
        if (null != mAMapLocationManager) {
            mAMapLocationManager.destroy();
            mAMapLocationManager = null;
        }
    }

}
